#include "BitmapFont.h"

#include "../SGD Wrappers/SGD_GraphicsManager.h"
#include "../TinyXML/tinyxml.h"
#include <ctype.h>
#include <cassert>

/**************************************************************/
// Initialize
//	- configure the font for "SGD_Font_Glow.png"
//	- probably should have parameters / config file
bool BitmapFont::Initialize(const char * xmlFilePath, const char* graphicsFont)
{
	m_hImage = SGD::GraphicsManager::GetInstance()->
		LoadTexture(graphicsFont); 

	//Making the TinyXML Doc
	TiXmlDocument bitmapReader;

	if (bitmapReader.LoadFile(xmlFilePath) == false)
		return false; 

	TiXmlElement *pRoot = bitmapReader.RootElement();

	if (pRoot == nullptr)
		return false;

	// Finding count
	TiXmlElement* pChars = pRoot->FirstChildElement("chars"); 

	int charCount = -1; //failcase

	pChars->Attribute("count", &charCount ); 

	if (charCount == -1)
		return false; 

	unsigned int* countValues = new unsigned int [charCount]; 

	TiXmlElement* pChar = pChars->FirstChildElement("char");

	int charSpotHolder = 0;
	int rectX = 0; 
	int rectY = 0; 
	int rectWidth = 0; 
	int rectHeight = 0; 
	int yOffsetSpot = 0; 


	for (int i = 0; i < charCount; i++)
	{
		pChar->Attribute("id", &charSpotHolder);
		pChar->Attribute("x", &rectX); 
		pChar->Attribute("y", &rectY); 
		pChar->Attribute("width", &rectWidth); 
		pChar->Attribute("height", &rectHeight); 
		pChar->Attribute("yoffset", &yOffsetSpot);

		m_rCells[charSpotHolder].left = (float)rectX + 4; 
		m_rCells[charSpotHolder].top = (float)rectY; 
		m_rCells[charSpotHolder].right = (float)rectX + rectWidth; 
		m_rCells[charSpotHolder].bottom = (float)rectY + rectHeight; 

		yOffsets[charSpotHolder] = yOffsetSpot; 

		pChar = pChar->NextSiblingElement();
		
	}

	delete countValues; 
	countValues = nullptr;

	return true; 
}

void BitmapFont::Terminate(void)
{
	SGD::GraphicsManager::GetInstance()->UnloadTexture(m_hImage);
}

void BitmapFont::Draw(const char* output, int x, int y,
	float scale, SGD::Color color) const
{
	assert(m_hImage != SGD::INVALID_HANDLE && "BitmapFont::Draw image not set"); 

	assert(output != nullptr && "BitmapFont::Draw output not set"); 

	int colX = x; 

	for (int i = 0; i < output[i]; i++)
	{
		char ch = output[i]; 

		if (ch == ' ')
		{
			x += (int)(20 * scale); 
			continue;
		}
		else if (ch == '\n')
		{
			y += (int)(20 * scale); 
			x = colX; 
			continue; 
		}
		else if (ch == '\t')
		{
			int pixels = x - colX; 

			int diff = pixels / 20 * (int)scale;

			int spaces = 4 - (diff % 4); 

			x += (int)(spaces * ((float)20 * scale)); 
			continue; 
		}


		SGD::GraphicsManager::GetInstance()->DrawTextureSection(
			m_hImage, { (float)x , (float)y + yOffsets[ch] }, m_rCells[ch],
			0, { 0, 0 }, color, { scale, scale });

		x += (int)(m_rCells[ch].ComputeWidth() * scale); 
	}

}